package me.jessyan.armscomponent.commonsdk.core;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;

import me.jessyan.armscomponent.commonsdk.utils.SPUtils;


/**
 * @author: Taozebi
 * @Date: 2020年9月9日16:52:07
 * @Description: 账号相关数据操作
 */
public class AccountDataProvider {
    private static AccountDataProvider mInstance;
    private static SPUtils spUtils;
    private String USER_INFO = "user_info";
    private String USER_ID = "user_id";
    private String TOKEN = "token";
    private String AUTOMATIC_LOGON = "automatic_logon";
    private String REMEMBER_PASSWORD = "remember_password";

    private AccountDataProvider() {
    }

    public static AccountDataProvider getInstance(Context context) {
        if (mInstance == null) {
            synchronized (AccountDataProvider.class) {
                if (mInstance == null) {
                    mInstance = new AccountDataProvider();
                }
            }
        }
        if(spUtils == null){
            synchronized (SPUtils.class) {
                if (spUtils == null) {
                    spUtils = new SPUtils(context, Constants.NAME_ACCOUNT_PREFS);
                }
            }
        }
        return mInstance;
    }

    public void cacheUser(User user){
        if(user != null){
            spUtils.putString(USER_INFO, new Gson().toJson(user));
        }
    }

    public User getUser() {
        String json = spUtils.getString(USER_INFO);
        if(TextUtils.isEmpty(json)){
            return null;
        }
        return new Gson().fromJson(json,User.class);
    }

    public void cacheUserId(String userId){
        spUtils.putString(USER_ID, userId);
    }

    public String getUserId() {
        return spUtils.getString(USER_ID);
    }

    public void cacheUserToken(String token){
        spUtils.putString(TOKEN, token);
    }

    public String getUserToken() {
        return spUtils.getString(TOKEN);
    }



    public void setRememberPassword(boolean rememberPassword){
        spUtils.putBoolean(REMEMBER_PASSWORD,rememberPassword);
    }

    /**
     * 是否记住密码
     * @return
     */
    public boolean isRememberPassword() {
        return spUtils.getBoolean(REMEMBER_PASSWORD,false);
    }
    public void setAutomaticLogon(boolean automaticLogon){
        spUtils.putBoolean(AUTOMATIC_LOGON,automaticLogon);
    }

    /**
     * 是否自动登录
     * @return
     */
    public boolean isAutomaticLogon() {
        return spUtils.getBoolean(AUTOMATIC_LOGON,false);
    }




    public void clearData() {
        spUtils.remove(REMEMBER_PASSWORD);
        spUtils.remove(AUTOMATIC_LOGON);
        spUtils.remove(USER_INFO);

    }
}
